<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ecard extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('ecard_model','ecard');
	}

	public function index()
	{
		$conf = array(
			'status' => 1
		);
		$ecards = $this->ecard->lists($conf);
		$data = array(
			'ecards' => $ecards
		);
		$this->load->view('templates/header');
		$this->load->view('ecard/index',$data);
		$this->load->view('templates/footer');
	}
	
	//白板创建(预留)
	public function create(){
		$this->load->helper('form');
		$this->load->view('templates/header');
		$this->load->view('ecard/create');
		$this->load->view('templates/footer');
	}
	
	//创建名片
	public function makeEcard(){
		$this->load->helper('form');
		$id = $this->uri->segment(3);//取得id
		$data = array(
			'ecard' => $this->ecard->getEcardInfo($id),
			'fonts' => array(
				'simhei.ttf'=>'黑体','simkai.ttf'=>'楷体','simsun.ttc'=>'宋体','simfang.ttf'=>'仿宋','msyh.ttf'=>'微软雅黑','msyhbd.ttf'=>'微软雅黑粗体'
			),
			'fontSize' => array('12','14','16','18','20')
		);
		
		$this->load->model('ecardAttr_model','attr');
		$data['attrs'] = $this->attr->getEcardAttr($id);
	
		$this->load->view('templates/header');
		$this->load->view('ecard/makeEcard',$data);
		$this->load->view('templates/footer');
	}
	
	//进一步确认创建名片
	public function confirm(){
		
		$this->load->helper("form");
		$act = $this->input->post('act');
		//初始化页面
		if( empty($act)){
		
			$id = $this->uri->segment(3);
			$data = array (
				'ecardinfo' => $this->ecard->userEcardInfo($id)
			);
			$this->load->view('templates/header');
			$this->load->view('ecard/confirm',$data);
			$this->load->view('templates/footer');
		}
		
		else{
			 if( $act == 'update'){
					//$this->load->library('form')
					$data = array(
						'title' => $this->input->post('title'),
						'is_using' => (int)$this->input->post('is_using')		
					);
					
					if($this->ecard->updateEcard($data,array('id'=>$this->input->post('id')) )){
						$result['error'] = 0;
						echo json_encode($result);
						exit;
						
					}else{
						$result['error'] = 1;
						 echo json_encode($result);
						 exit;
					}
			 }
		}
		
	}
	
	public function download(){
		$file = $this->input->post('filename');
		if(file_exists($file))
		downloadFile('download.'.end(explode('.',$file)),file_get_contents($file));
		else exit('file not exists:'.$file) ;
	} 
	
	
	//用户的名片列表
	public function ecardList(){
		$this->load->model("user_model",'user');
		
		//登陆操作
		if (!$this->user->islogin()){
			set_session('crefresh','ecard/ecardList');
			showMessage();
		}
		
		
		$data = array(
			'ecards' => $this->ecard->userEcard(guser('id'))
		);

		
		$this->load->view("templates/header");
		$this->load->view("ecard/list",$data);
		$this->load->view("templates/footer");
	}
	
	
	/*
	* 执行生成名片
	*/
	public function createAction(){
	
		global $msaterimg;//母版
		 
		$this->load->library('image_lib');
		$attrs = $this->input->post('attr');//文本属性,$this->input->post只能获得文本属性，图像等媒体节点另外处理
		$attrname = $this->input->post('attrname');//属性名
		$attrtypes = $this->input->post('attrtype');//属性的类型
		$attrid = $this->input->post('attrid');//属性ID
		$attrcoordinate = $this->input->post('coordinate');//属性的定位坐标
		$sizes = $this->input->post('size');//属性尺寸限制
		$master = $this->input->post('master');//底版图像，名片的母版
		
		//取消字体样式排版
		//$fonts = $this->input->post('font');//字体
		//$fontsize = $this->input->post('fontSize');//字体大小
		//$fontcolor = $this->input->post('fontColor');//字体颜色
		
		$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/msyh.ttf';
		$config['wm_font_size'] = 12;
		
		
		$config['source_image'] =  FCPATH.$master;//原图的路径;
		
		//水印默认配置
		
		$config['image_library'] = 'GD2';//使用gd2库
		$config['quality'] = 100; //图片的质量，1-100 值越大质量越高，文件也相应越大
		$config['create_thumb'] = FALSE;//不创建缩略图
	
		
		$master_imageinfo = explode('.',$master);
		
		//标识第几个文本属性，由于文本属性和图像属性是同时传入，所以无法在循环中标识
		$offsetattr = 0;
		
		$up_config['allowed_types'] = 'png';
		
		foreach($attrtypes as $key => $attrtype){
		
			//第一次处理图像，复制一个新图，防止原模板被更改
			if($key == 0){
				$new_img_name = $master_imageinfo[0].time().floor(microtime()*1000).".".end($master_imageinfo);
				$msaterimg = $config['new_image'] = FCPATH.'data/upload/ecard/'.$new_img_name;//设置图像的目标名/路径。
			}else{
				$config['source_image'] = $msaterimg;
				unset($config['new_image']);
			}
			
			$config['wm_vrt_alignment'] = 'top';//水印的垂直排布方式，结合水印的偏移量，决定水印位置
			$config['wm_hor_alignment'] = 'left';//水印的水平排布方式，同上

			$coordinate = explode('|',$attrcoordinate[$key]);  //解析坐标
			$config['wm_hor_offset'] = $coordinate[0];  //水平偏移量,wm_hor_alignment设置为right，所以是向右偏移
			$config['wm_vrt_offset'] = $coordinate[1];  //垂直偏移量,wm_vrt_alignment设置为top，所以是向下偏移
			
			
			//文本水印
			if($attrtype == 0 || $attrtype == 1){
				$size = $sizes[$key];
				$attr = $attrs[$offsetattr];
				$offsetattr++;//文本类型向前推进
				$attrlength = mb_strlen($attr);
				if( $attrlength > $size || $attrlength == 0){
					$result['error'] = "{$attrname[$key]}字数在1-{$size}!";
					echo json_encode($result);
					exit;
				}
			
		
				$config['wm_text'] =  $attr;//文本
				$config['wm_type'] = 'text';//水印类型为 ‘text’
				//$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/'.$fonts[$key];//字体
				//$config['wm_font_size'] = $fontsize[$key];//字号
				//$config['wm_font_color'] = str_replace('#','',$fontcolor[$key]);//字体颜色
				$config['wm_padding'] = '0';//内容padding偏移，用于左右同时等量移动
				
				
				
			//图片水印			
			}elseif($attrtype  == 2){
				
				$size = explode('|',$sizes[$key]);
				$this->load->model('upload_model');
				$up_config['upload_path'] = './data/upload/ecard/';
				$up_config['max_width']  = $size[0];
				$up_config['max_height']  = $size[1];
				
				$img = $this->upload_model->upload("image_".$key,$up_config);
				
				if(isset($img['error'])){
					$result['error'] = $img['error'];
					echo json_encode($result);
					exit;
				}
				
				//计算图片真实的偏移量：图片可能不是全尺寸，所以要重新计算偏移量  
				//上偏移量 = (图片最大高 - 上传图片的高度) / 2 + 设置的的上偏移量 
				//左偏移量同理
				$config['wm_hor_offset'] = (int)($size[0] - $img['image_width']) / 2 + $config['wm_hor_offset'] ;
				$config['wm_vrt_offset'] =  (int)($size[1] - $img['image_height']) / 2 + $config['wm_vrt_offset'];
			
				
				$config['wm_overlay_path'] = FCPATH.$up_config['upload_path'].$img['file_name'];
				$config['wm_type'] = 'overlay';
				$config['wm_opacity'] = 100;//水印透明度,可以使水印模糊化 1-100
				
				//水印透明度
				//$config['wm_x_transp'] = '';
				//$config['wm_y_transp'] = '';
				
			//图片或文本 结合 只需取其一
			}elseif($attrtype == 3){
					$attr = $attrs[$offsetattr];
				
				
				//如果文本为空，则可能是图像
				if( $attr == ""){
					 
						//图像也为空
					 	if(!isset($_FILES["image_".$key]['tmp_name']) ||  $_FILES["image_".$key]['tmp_name'] == ""){
						
							$result['error'] = "{$attrname[$key]}必须填写!";
							echo json_encode($result);
							exit;
							
						//有图像则上传
						}else{
									$size = explode('|',$sizes[$key]);
									$this->load->model('upload_model');
									$up_config['upload_path'] = './data/upload/ecard/';
									$up_config['max_width']  = $size[0];
									$up_config['max_height']  = $size[1];
							
									$img = $this->upload_model->upload("image_".$key,$up_config);
							
									if(isset($img['error'])){
										$result['error'] = $img['error'];
										echo json_encode($result);
										exit;
									}
									
								
									//计算图片真实的偏移量：图片可能不是全尺寸，所以要重新计算偏移量  如 上偏移量 = (图片最大高 - 上传图片的高度) / 2 + 本图层的偏移量
									$config['wm_vrt_offset'] =  (int)($size[1] - $img['image_height']) / 2 + $config['wm_vrt_offset'];
									$config['wm_hor_offset'] = (int)($size[0] - $img['image_width']) / 2 + $config['wm_hor_offset'] ;
									
									$config['wm_overlay_path'] = FCPATH.$up_config['upload_path'].$img['file_name'];
									$config['wm_type'] = 'overlay';
									$config['wm_opacity'] = 100;//水印透明度,可以使水印模糊化 1-100
						}
				
				//有文本内容
				}else{
					
					$size = explode('|',$sizes[$key]);
					$attr = $attrs[$offsetattr];
					$attrlength = mb_strlen($attr);
					if( $attrlength > $size[2] || $attrlength == 0){
						$result['error'] = "{$attrname[$key]}字数在1-{$size[2]}!";
						echo json_encode($result);
						exit;
					}
					$config['wm_text'] =  $attr;//文本
					$config['wm_type'] = 'text';
					
				
					
				//$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/'.$fonts[$key];//黑体
				//$config['wm_font_size'] = $fontsize[$key];
				//$config['wm_font_color'] = str_replace('#','',$fontcolor[$key]);
				$config['wm_padding'] = '0';//内容padding偏移，用于左右同时等量移动
					
					
					
				}
				$offsetattr++;//文本类型向前推进
			}
			
			
			$this->image_lib->initialize($config);

			if ( ! $this->image_lib->watermark())
			{
				$result['error'] = $this->image_lib->display_errors('','');
				echo json_encode($result);
				exit;
			}
			
			
			 //$this->image_lib->clear();
			
		}	
			//添加记录到用户
			$result['ecard_id'] = $this->ecard->addUserEcard(guser('id'),'data/upload/ecard/'.$new_img_name);
			$result['error'] = 0;
			$result['image'] = 'data/upload/ecard/'.$new_img_name;
			echo json_encode($result);
			exit;		
	}	
	
	/*
	* 预览名片
	*/
	public function createPreview(){
	
		global $msaterimg;//母版
		$is_preview = false;//是否可预览,
		$this->load->library('image_lib');
		$attrs = $this->input->post('attr');//文本属性,$this->input->post只能获得文本属性，图像等媒体节点另外处理
		$attrname = $this->input->post('attrname');//属性名
		$attrtypes = $this->input->post('attrtype');//属性的类型
		$attrid = $this->input->post('attrid');//属性ID
		$attrcoordinate = $this->input->post('coordinate');//属性的定位坐标
		$sizes = $this->input->post('size');//属性尺寸限制
		$master = $this->input->post('master');//底版图像，名片的母版
		
		//取消字体样式排版
		//$fonts = $this->input->post('font');//字体
		//$fontsize = $this->input->post('fontSize');//字体大小
		//$fontcolor = $this->input->post('fontColor');//字体颜色
		
		$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/msyh.ttf';
		$config['wm_font_size'] = 12;
		
		
		$config['source_image'] =  FCPATH.$master;//原图的路径;
		
		//水印默认配置
		
		$config['image_library'] = 'GD2';//使用gd2库
		$config['quality'] = 100; //图片的质量，1-100 值越大质量越高，文件也相应越大
		
		
		$config['create_thumb'] = FALSE;//不创建缩略图
		
		$master_imageinfo = explode('.',$master);//底版信息
		
		//标识第几个文本属性，由于文本属性和图像属性是同时传入，所以无法在循环中标识
		$offsetattr = 0;
		
		$up_config['allowed_types'] = 'png';
		
		//创建
		foreach($attrtypes as $key => $attrtype){
		
			//第一次处理图像，复制一个新图，防止原模板被更改
			if($key == 0){
				$new_img_name = $master_imageinfo[0].time().floor(microtime()*1000).".".end($master_imageinfo);
				$msaterimg = $config['new_image'] = FCPATH.'data/upload/ecard/'.$new_img_name;//设置图像的目标名/路径。
				
			//其他情况，不新建图像 ，在同一图像上操作	
			}else{
				$config['source_image'] = $msaterimg;
				unset($config['new_image']);
			}
			
			$config['wm_vrt_alignment'] = 'top';//水印的垂直排布方式，结合水印的偏移量，决定水印位置
		    $config['wm_hor_alignment'] = 'left';//水印的水平排布方式，结合水印的偏移量，决定水印位置

			$coordinate = explode('|',$attrcoordinate[$key]);  //解析坐标
			$config['wm_hor_offset'] = $coordinate[0];  //水平偏移量,wm_hor_alignment设置为right，所以是向右偏移
			$config['wm_vrt_offset'] = $coordinate[1];  //垂直偏移量,wm_vrt_alignment设置为top，所以是向下偏移
			
			
			//文本水印
			if($attrtype == 0 || $attrtype == 1){
				$size = $sizes[$key];
				$attr = $attrs[$offsetattr];
				$offsetattr++;//文本类型向前推进
				if($attr == ""){
						continue;
				}
				$attrlength = mb_strlen($attr);
				if( $attrlength > $size || $attrlength == 0){
					$result['error'] = "{$attrname[$key]}字数在1-{$size}!";
					echo json_encode($result);
					exit;
				}
				$config['wm_text'] =  $attr;//文本
				$config['wm_type'] = 'text';
				
		
				//$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/'.$fonts[$key];
				//$config['wm_font_size'] = $fontsize[$key];
			//	$config['wm_font_color'] = str_replace('#','',$fontcolor[$key]);
				$config['wm_padding'] = '0';//内容padding偏移，用于左右同时等量移动
				
				
				$is_preview = true;

			}
			
			//图片水印		
			elseif($attrtype  == 2){
				if( ! isset($_FILES["image_".$key]['tmp_name']) ||  $_FILES["image_".$key]['tmp_name'] == "" ){
						continue;
				}
				
				$size = explode('|',$sizes[$key]);
				$this->load->model('upload_model');
				
				$up_config['max_width'] = $size[0];
				$up_config['max_height'] = $size[1];
				$up_config['upload_path'] = './data/upload/ecard/';
				
				$img = $this->upload_model->upload("image_".$key,$up_config);
				
				if(isset($img['error'])){
					$result['error'] = $img['error'];
					echo json_encode($result);
					exit;
				}
				
				
				//计算图片真实的偏移量：图片可能不是全尺寸，所以要重新计算偏移量  
				//上偏移量 = (图片最大高 - 上传图片的高度) / 2 + 设置的的上偏移量 
				//左偏移量同理
				$config['wm_vrt_offset'] =  (int)($size[1] - $img['image_height']) / 2 + $config['wm_vrt_offset'];
			    $config['wm_hor_offset'] = (int)($size[0] - $img['image_width']) / 2 + $config['wm_hor_offset'] ;
				
				$config['wm_overlay_path'] = FCPATH.$up_config['upload_path'].$img['file_name'];
				$config['wm_type'] = 'overlay';
				$config['wm_opacity'] = 100;//水印透明度,可以使水印模糊化 1-100
				
				//水印透明度
				//$config['wm_x_transp'] = '';
				//$config['wm_y_transp'] = '';
				$is_preview = true;
			}
			
			//图片或文本 结合 只需取其一
			elseif($attrtype == 3){
					$attr = $attrs[$offsetattr];
				
				//如果文本为空，则可能是图像
				if( $attr == "" ){
					
						//图像也为空
					 	if( ! isset($_FILES["image_".$key]['tmp_name']) ||  $_FILES["image_".$key]['tmp_name'] == "" ){
								continue;
						//有图像则上传
						}else{
							
									$size = explode('|',$sizes[$key]);
									$this->load->model('upload_model');
									
									
									$up_config['max_width']  = $size[0];
									$up_config['max_height']  = $size[1];
									print_r($up_config);
									$up_config['upload_path'] = './data/upload/ecard/';

							
									$img = $this->upload_model->upload("image_".$key,$up_config);
									if(isset($img['error'])){
										$result['error'] = $img['error'];
										echo json_encode($result);
										exit;
									}
									
									//计算图片真实的偏移量：图片可能不是全尺寸，所以要重新计算偏移量  
									//上偏移量 = (图片最大高 - 上传图片的高度) / 2 + 设置的的上偏移量 
									//左偏移量同理
									$config['wm_vrt_offset'] =  (int)($size[1] - $img['image_height']) / 2 + $config['wm_vrt_offset'];
									$config['wm_hor_offset'] = (int)($size[0] - $img['image_width']) / 2 + $config['wm_hor_offset'] ;
									
									$config['wm_overlay_path'] = FCPATH.$up_config['upload_path'].$img['file_name'];
									$config['wm_type'] = 'overlay';
									$config['wm_opacity'] = 100;//水印透明度,可以使水印模糊化 1-100
									
									$is_preview = true;
						}
				
				//有文本内容
				}else{
				
						$size = explode('|',$sizes[$key]);
					$attr = $attrs[$offsetattr];
					$attrlength = mb_strlen($attr);
					if( $attrlength > $size[2] || $attrlength == 0){
							$result['error'] = "{$attrname[$key]}字数在1-{$size[2]}!";
						echo json_encode($result);
						exit;
					}
					$config['wm_text'] =  $attr;//文本
					$config['wm_type'] = 'text';
					
				
					
					//$config['wm_font_path'] =  FCPATH.$this->config->item('public').'assets/fonts/'.$fonts[$key];//黑体
					//$config['wm_font_size'] = $fontsize[$key];
					//$config['wm_font_color'] = str_replace('#','',$fontcolor[$key]);
					$config['wm_padding'] = '0';//内容padding偏移，用于左右同时等量移动
					
					
					$is_preview = true;
					
				}
				
				$offsetattr++;//文本类型向前推进
			}
			
			
			$this->image_lib->initialize($config);
			if($is_preview){
				if ( ! $this->image_lib->watermark())
				{
					$result['error'] = $this->image_lib->display_errors();
					//$result['config'] = $config;
					echo json_encode($result);
					exit;
				}
				
				
				//更多坐标，表示当前属性需要被多次利用
				if(count($coordinate) >2){
				
					$attrcount = ceil(count($coordinate)/2);//每两个坐标值定位一个坐标点
					
					//当前坐标点是第二个,所以$i=1
					for($i=1;$i<$attrcount;$i++){
						$config['wm_hor_offset'] = (int)$coordinate[$i*2];  //水平偏移量,wm_hor_alignment设置为right，所以是向右偏移
						if(isset($coordinate[$i*2+1])){
							$config['wm_vrt_offset'] = (int)$coordinate[$i*2+1];  //垂直偏移量,wm_vrt_alignment设置为top，所以是向下偏移
						}
						
					
						
						//图像类别
						if(($attrtype == 3 || $attrtype == 2) && $i==1){
							//缩略图
							
							//给水印图层创建小的缩略图*/
							$config['source_image'] = $config['new_image'];
							$config['wm_overlay_path'] = $this->resizeImage($config['wm_overlay_path'],'20','5');
							$this->image_lib->initialize($config);
							$this->image_lib->watermark();
							
							
						}

						//清除生成新图片的设置，并且把当前的图片作为原图
						if(isset($config['new_image'])){
							$config['source_image'] = $config['new_image'];
							unset($config['new_image']);
						}
						
				
						$this->image_lib->initialize($config);
						//print_r($config);
						$this->image_lib->watermark();
					}
				
				}
			}
			
			 //$this->image_lib->clear();
			
		}	//foreach 创建 end
		
		//成功，输出
		if($is_preview){
			$result['error'] = 0;
			$result['image'] = 'data/upload/ecard/'.$new_img_name;
			$result['result_image'] = $new_img_name;
			
			echo json_encode($result);
			exit;
		}else{
			$result['error'] = "请输入项目后预览";
	
			echo json_encode($result);
			exit;
		}
		
		
	}
	
	//缩略缩略图片
	function resizeImage($image,$width,$height){
	
		$this->load->library('image_lib');
		$config['source_image'] = $image;
		$config['create_thumb'] = TRUE;
		$config['width'] = $width;
		$config['height'] = $height;

		$config['new_image'] = str_replace(strrchr($image, "."),"",$image)."_thumb".strrchr($image, ".");
		
		$this->image_lib->initialize($config);
		$this->image_lib->resize();
		return $config['new_image'];
	}

	//	清除临时文件
	function clearImage(){
		
		$img = 'data/upload/ecard/'.$this->input->post('img');
		if(file_exists($img )){
			unlink($img);
		}else{
			echo "no file";
		}
	}
	
}